package org.jsets.fastboot.security.authc;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jsets.fastboot.model.BaseResp;
import org.jsets.fastboot.security.SecurityUtils;
import org.jsets.fastboot.util.JsonUtils;
import org.jsets.fastboot.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;

public class AuthcExceptionHandlerImpl implements IAuthcExceptionHandler {

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
		int httpStatus =  HttpStatus.UNAUTHORIZED.value();
		int code = httpStatus;
		if(authException instanceof InsufficientAuthenticationException) {
			code = SecurityUtils.getProperties().getInsufficientAuthenticationCode();
		}
		BaseResp resp = BaseResp.fail(code, authException.getMessage());
		WebUtils.writeJsonToResponse(response, httpStatus, JsonUtils.toJson(resp));
	}

}